package com.hospital.hospitalsystem.config;

import com.hospital.hospitalsystem.base.MyException;
import com.hospital.hospitalsystem.entity.UserExt;
import com.hospital.hospitalsystem.utils.LoginUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/22
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(!method.isAnnotationPresent(TokenVerify.class)){
            return true;
        }else {
            String token = request.getHeader("token");
            UserExt userExt = LoginUtils.getUser(token);
            String type = userExt.getRoles();
            TokenVerify passToken = method.getAnnotation(TokenVerify.class);
            List<String> arrayList = Arrays.asList(passToken.type().split(","));
            if (arrayList.contains(type)){
                return true;
            }else {
                throw new MyException("当前权限不允许调用此接口");
            }
        }
    }
}
